"""
请求计数器模块
用于统计HTTP请求数量
"""
import threading
import time
from collections import defaultdict
from datetime import datetime, timedelta
from django.utils import timezone


class RequestCounter:
    """请求计数器"""
    
    def __init__(self):
        self._lock = threading.RLock()
        self._total_requests = 0
        self._request_timestamps = []  # 存储最近的请求时间戳
        self._max_timestamps = 1000  # 最多保存1000个时间戳
        
    def increment(self):
        """增加请求计数"""
        with self._lock:
            self._total_requests += 1
            current_time = time.time()
            self._request_timestamps.append(current_time)
            
            # 清理超过1小时的时间戳
            cutoff_time = current_time - 3600  # 1小时前
            self._request_timestamps = [
                ts for ts in self._request_timestamps 
                if ts > cutoff_time
            ]
            
            # 限制时间戳数量
            if len(self._request_timestamps) > self._max_timestamps:
                self._request_timestamps = self._request_timestamps[-self._max_timestamps:]
    
    def get_total_requests(self) -> int:
        """获取总请求数"""
        with self._lock:
            return self._total_requests
    
    def get_requests_per_minute(self) -> float:
        """获取每分钟请求数（基于最近1分钟的数据）"""
        with self._lock:
            current_time = time.time()
            cutoff_time = current_time - 60  # 1分钟前
            
            recent_requests = [
                ts for ts in self._request_timestamps 
                if ts > cutoff_time
            ]
            
            return len(recent_requests)
    
    def get_requests_per_hour(self) -> int:
        """获取每小时请求数（基于最近1小时的数据）"""
        with self._lock:
            current_time = time.time()
            cutoff_time = current_time - 3600  # 1小时前
            
            recent_requests = [
                ts for ts in self._request_timestamps 
                if ts > cutoff_time
            ]
            
            return len(recent_requests)
    
    def reset(self):
        """重置计数器"""
        with self._lock:
            self._total_requests = 0
            self._request_timestamps = []


# 全局请求计数器实例
_request_counter = RequestCounter()


def get_request_counter() -> RequestCounter:
    """获取全局请求计数器实例"""
    return _request_counter


class RequestCounterMiddleware:
    """请求计数中间件"""
    
    def __init__(self, get_response):
        self.get_response = get_response
        self.counter = get_request_counter()
    
    def __call__(self, request):
        # 增加请求计数
        self.counter.increment()
        
        response = self.get_response(request)
        return response